package com.cdu.ai_intelligent_teaching_and_training_system.controller;

import com.cdu.ai_intelligent_teaching_and_training_system.dto.ApiResponse;
import com.cdu.ai_intelligent_teaching_and_training_system.dto.LoginRequest;
import com.cdu.ai_intelligent_teaching_and_training_system.dto.LoginResponse;
import com.cdu.ai_intelligent_teaching_and_training_system.entity.Student;
import com.cdu.ai_intelligent_teaching_and_training_system.entity.Teacher;
import com.cdu.ai_intelligent_teaching_and_training_system.entity.User;
import com.cdu.ai_intelligent_teaching_and_training_system.mapper.StudentMapper;
import com.cdu.ai_intelligent_teaching_and_training_system.mapper.TeacherMapper;
import com.cdu.ai_intelligent_teaching_and_training_system.service.UserService;
import com.cdu.ai_intelligent_teaching_and_training_system.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/auth")
@CrossOrigin(origins = "*")
public class AuthController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private TeacherMapper teacherMapper;
    
    @Autowired
    private StudentMapper studentMapper;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<LoginResponse>> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            User user = userService.findByUsername(loginRequest.getUsername())
                    .orElse(null);
            
            if (user == null) {
                return ResponseEntity.ok(ApiResponse.error("用户名或密码错误"));
            }
            
            if (!userService.validatePassword(loginRequest.getPassword(), user.getPassword())) {
                return ResponseEntity.ok(ApiResponse.error("用户名或密码错误"));
            }
            
            LoginResponse loginResponse = new LoginResponse();
            loginResponse.setToken(jwtUtil.generateToken(user.getUsername(), user.getRole(), user.getUserId()));
            loginResponse.setUsername(user.getUsername());
            loginResponse.setRole(user.getRole());
            loginResponse.setUserId(user.getUserId());
            
            // 根据角色获取姓名
            if ("teacher".equals(user.getRole())) {
                Teacher teacher = teacherMapper.selectByUserId(user.getUserId());
                if (teacher != null) {
                    loginResponse.setName(teacher.getName());
                }
            } else if ("student".equals(user.getRole())) {
                Student student = studentMapper.selectByUserId(user.getUserId());
                if (student != null) {
                    loginResponse.setName(student.getName());
                }
            }
            
            return ResponseEntity.ok(ApiResponse.success("登录成功", loginResponse));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("登录失败：" + e.getMessage()));
        }
    }
    
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<String>> register(@Valid @RequestBody User user) {
        try {
            if (userService.existsByUsername(user.getUsername())) {
                return ResponseEntity.ok(ApiResponse.error("用户名已存在"));
            }
            
            if (userService.existsByEmail(user.getEmail())) {
                return ResponseEntity.ok(ApiResponse.error("邮箱已存在"));
            }
            
            userService.save(user);
            return ResponseEntity.ok(ApiResponse.success("注册成功", null));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("注册失败：" + e.getMessage()));
        }
    }
} 